package com.greenline.push.common.utils;

import java.io.IOException;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.xml.ResourceEntityResolver;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;

public class BeanLoaderUtil implements ApplicationContextAware {
    private ConfigurableApplicationContext applicationContext = null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = (ConfigurableApplicationContext) applicationContext;
    }

    public ConfigurableApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public void loadBean(String configuration) {
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader((BeanDefinitionRegistry) getApplicationContext().getBeanFactory());
        reader.setResourceLoader(getApplicationContext());
        reader.setEntityResolver(new ResourceEntityResolver(getApplicationContext()));
        String[] configurations = new String[] { configuration };
        for (int i = 0; i < configurations.length; i++) {
            try {
                reader.loadBeanDefinitions(getApplicationContext().getResources(configurations[i]));
            } catch (BeanDefinitionStoreException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
